package com.gimi.cloud.jimi.manage.service.prod.impl;

import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.MyBeanUtils;
import com.gimi.cloud.jimi.common.utils.Page;
import com.gimi.cloud.jimi.commonService.common.JmOperationLogService;
import com.gimi.cloud.jimi.dao.dao.prod.ProdCatModelDao;
import com.gimi.cloud.jimi.dao.dao.prod.ProdCatModelValueDao;
import com.gimi.cloud.jimi.dao.dao.prod.ProdCategoryDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductSkuDao;
import com.gimi.cloud.jimi.dao.myMapper.core.query.QueryParam;
import com.gimi.cloud.jimi.dto.base.BaseDTO;
import com.gimi.cloud.jimi.dto.prod.ProdCatModelDTO;
import com.gimi.cloud.jimi.entity.prod.ProdCatModelEntity;
import com.gimi.cloud.jimi.entity.prod.ProdCatModelValueEntity;
import com.gimi.cloud.jimi.entity.prod.ProdCategoryEntity;
import com.gimi.cloud.jimi.manage.service.prod.ProdCatModelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @auther loongs
 * @date 2017/12/18  16:23
 */
@Service
public class ProdCatModelServiceImpl implements ProdCatModelService {
    private ProdCatModelDao prodCatModelDao;
    private ProdCategoryDao prodCategoryDao;
    private ProdCatModelValueDao prodCatModelValueDao;
    private ProductSkuDao productSkuDao;
    private JmOperationLogService jmOperationLogService;


    @Autowired
    public ProdCatModelServiceImpl(ProdCatModelDao prodCatModelDao,ProdCategoryDao prodCategoryDao,ProdCatModelValueDao prodCatModelValueDao,
                                   ProductSkuDao productSkuDao,JmOperationLogService jmOperationLogService) {
        this.prodCatModelDao = prodCatModelDao;
        this.prodCategoryDao = prodCategoryDao;
        this.prodCatModelValueDao=prodCatModelValueDao;
        this.jmOperationLogService=jmOperationLogService;
        this.productSkuDao=productSkuDao;
    }

    @Override
    public  Page<ProdCatModelDTO> getProdCatModelList(ProdCatModelDTO prodCatModelDTO) {
        PageHelper.startPage(prodCatModelDTO.getCurrentPage(), prodCatModelDTO.getPageSize());
        List<ProdCatModelDTO> result=prodCatModelDao.queryPageList(prodCatModelDTO);
        Page<ProdCatModelDTO> page =new Page(new PageInfo<>(result));
        return page;
    }

    @Override
    public List<ProdCatModelDTO> queryList(ProdCatModelDTO dto,boolean isPaging)  {
        if(isPaging){
            PageHelper.startPage(dto.getCurrentPage(),dto.getPageSize());
        }
        String sql ="SELECT model.*,cate.prod_cat_name,(SELECT GROUP_CONCAT(val.model_value) FROM ec_prod_cat_model_value val WHERE val.is_delete = 0 AND  val.model_id = model.model_id) all_model_value" +
                " FROM ec_prod_cat_model model" +
                " LEFT JOIN ec_prod_category cate ON cate.prod_cat_id = model.prod_cat_id" +
                " WHERE 1=1 and model.is_del = 1 AND model.prod_cat_id = :prodCatId ";
        QueryParam queryParam = new QueryParam();
        queryParam.setSql(sql);
        queryParam.setParamObject(dto);
        return prodCatModelDao.selectListDTOBySql(queryParam);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public ResponseCodeEnum addProdCatModel(ProdCatModelDTO prodCatModelDTO) {
        ProdCategoryEntity prodCategoryEntity=prodCategoryDao.selectByPrimaryKey(prodCatModelDTO.getProdCatId());
        //校验商品品类是否存在
        if(prodCategoryEntity == null){
            return ResponseCodeEnum.PRODCATID_IS_NOT_EXIT;
        }
        //校验品类是否为三级品类
        if(prodCategoryEntity.getCatGrade() != 3){
            return ResponseCodeEnum.PRODCATID_IS_NOT_RIGHT;
        }
        //通过品类id和属性名查询
        Example example=new Example(ProdCatModelEntity.class);
        example.createCriteria().andCondition("prod_cat_id=",prodCatModelDTO.getProdCatId()).
                andCondition("prod_prop_name=",prodCatModelDTO.getProdPropName());
        List<ProdCatModelEntity> prodCatModelEntityList=  prodCatModelDao.selectByExample(example);

        if(prodCatModelEntityList.size() > 0){
            throw new MsgException(ResponseCodeEnum.PRODCATMODEL_IS_EXIT);
        }
        ProdCatModelEntity prodCatModelEntity=new ProdCatModelEntity();
        //新增默认为可用
        prodCatModelDTO.setIsDel(1);
        BeanUtils.copyProperties(prodCatModelDTO,prodCatModelEntity);
        prodCatModelDao.insertReturnKey(prodCatModelDTO);

        //添加操作日志
        BaseDTO baseDTO=new BaseDTO();
        BeanUtils.copyProperties(prodCatModelDTO,baseDTO);
        jmOperationLogService.insertAddLog(baseDTO,prodCatModelDTO.getModelId()+"","addProdCatModel","ec_prod_cat_model","添加商品品类模板");
        return ResponseCodeEnum.SUCCESSED;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public ProdCatModelDTO saveOrUpdate(ProdCatModelDTO dto) {
        ProdCatModelEntity prodCatModelEntity = null;
        if(null != dto.getModelId()){
            prodCatModelEntity = prodCatModelDao.selectByPrimaryKey(dto.getModelId());
            if(null == prodCatModelEntity){
                throw new MsgException(ResponseCodeEnum.FAILURE,"未获取到id为"+dto.getModelId()+"的品类模版，保存失败");
            }
        }else{
            prodCatModelEntity = new ProdCatModelEntity();
        }
        int count = prodCatModelDao.selectCountByCatIdAndPropNameExcludeModelId(dto.getProdCatId(),dto.getProdPropName(),dto.getModelId());
        if(count > 0){
            throw new MsgException(ResponseCodeEnum.PRODCATMODEL_IS_EXIT_WHEN_EDIT,"品类模板‘"+dto.getProdPropName()+"’已经存在，请确认");
        }
        MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(dto,prodCatModelEntity);
        if(null != dto.getModelId()){
            prodCatModelDao.baseUpdateByPrimaryKey(prodCatModelEntity);
            //记录日志
            jmOperationLogService.insertUpdateLog(dto,"saveOrUpdate","ec_prod_cat_model",dto.getModelId()+"","编辑（修改）商品品类模板");
        }else{
            prodCatModelEntity.setIsDel(1);
            prodCatModelDao.baseInsert(prodCatModelEntity);
            //记录日志
            jmOperationLogService.insertAddLog(dto,dto.getModelId()+"","saveOrUpdate","ec_prod_cat_model","添加商品品类模板");
        }
        MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(prodCatModelEntity,dto);
        return dto;
    }

    @Override
    public int deleteProdCatModelByCatIdExcludeModelIds(BaseDTO dto, String prodCatdId, List<Long> modelIds){
        String sql ="UPDATE ec_prod_cat_model SET is_del = 0,update_uid ='"+dto.getUpdateUid()+"',update_uname ='"+dto.getUpdateUname()+"',update_time=NOW() " +
                "   WHERE is_del = 1 and prod_cat_id ='"+prodCatdId+"'";
        String modelIdStr = "";
        if(null != modelIds && modelIds.size() > 0){
            for (Long modelId:modelIds){
                modelIdStr+=modelId+",";
            }
        }
        if(modelIdStr.length()>1){
            modelIdStr = modelIdStr.substring(0,modelIdStr.length()-1);
            sql+=" AND model_id NOT in("+modelIdStr+");";
        }
        QueryParam queryParam = new QueryParam();
        queryParam.setSql(sql);
        return prodCatModelDao.updateSql(queryParam);
    }

    @Override
    public List<ProdCatModelDTO> getProdCatModelByCatId(ProdCatModelDTO dto, String catId)  {
        List<ProdCatModelDTO> prodCatModels = prodCatModelDao.queryEcprodCatModelByCatId(catId);
        if(null != prodCatModels && prodCatModels.size() > 0){
            for(ProdCatModelDTO prodCatmodel:prodCatModels){
                prodCatmodel.setProdCatModelValue(prodCatModelValueDao.queryPordCatModelValueByModelId(prodCatmodel.getModelId()));
            }
        }
        return prodCatModels;
    }

    @Override
    public ProdCatModelEntity gotoEditProdCatModel(ProdCatModelDTO prodCatModelDTO) {
        ProdCatModelEntity prodCatModelEntity= prodCatModelDao.selectByPrimaryKey(prodCatModelDTO.getModelId());
        //添加操作日志
        jmOperationLogService.insertQueryLog(new BaseDTO(),"gotoEditProdCatModel","ec_prod_cat_model",
                prodCatModelDTO.getModelId()+"","转跳到编辑界面");
        return prodCatModelEntity;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public ResponseCodeEnum editProdCatModel(ProdCatModelDTO prodCatModelDTO) {
        //判断是否能删除、禁用或者启用、编辑
        ProdCatModelEntity isPublishedEntity = prodCatModelDao.selectProductIsPublished(prodCatModelDTO.getModelId());
        if(isPublishedEntity != null){
            throw new MsgException(ResponseCodeEnum.FAILURE,"编辑失败，该品类模板值已上架，请确认后重试！");
        }
        //通过品类id和属性名查询
        Example example=new Example(ProdCatModelEntity.class);
        example.createCriteria().andCondition("prod_cat_id=",prodCatModelDTO.getProdCatId()).
                andCondition("prod_prop_name=",prodCatModelDTO.getProdPropName());
        List<ProdCatModelEntity> prodCatModelEntityList=  prodCatModelDao.selectByExample(example);
        //判断模板是否存在，且不等于自身
        if(prodCatModelEntityList.size() > 0 && prodCatModelDTO.getModelId().intValue()!=prodCatModelEntityList.get(0).getModelId().intValue()){
            throw new MsgException(ResponseCodeEnum.PRODCATMODEL_IS_EXIT_WHEN_EDIT);
        }

        ProdCatModelEntity prodCatModelEntity = new ProdCatModelEntity();
        BeanUtils.copyProperties(prodCatModelDTO,prodCatModelEntity);
        ProdCatModelEntity prodCatModelEntityTemp=prodCatModelDao.selectByPrimaryKey(prodCatModelDTO.getModelId());
        //将原来的禁用或启用，重新赋值给对象
        prodCatModelEntity.setIsDel(prodCatModelEntityTemp.getIsDel());
        prodCatModelDao.updateByPrimaryKeySelective(prodCatModelEntity);

        //添加操作日志
        BaseDTO baseDTO=new BaseDTO();
        BeanUtils.copyProperties(prodCatModelDTO,baseDTO);
        jmOperationLogService.insertUpdateLog(baseDTO,"editProdCatModel","ec_prod_cat_model",prodCatModelDTO.getModelId()+"","编辑（修改）商品品类模板");

        return ResponseCodeEnum.SUCCESSED;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public ResponseCodeEnum deleteProdCatModel(ProdCatModelDTO prodCatModelDTO) {
        ProdCatModelEntity prodCatModelEntity=prodCatModelDao.selectByPrimaryKey(prodCatModelDTO.getModelId());
        if(prodCatModelEntity == null){
            return ResponseCodeEnum.PRODCATMODEL_IS_NOT_EXIT;
        }
        //判断是否能删除、禁用或者启用、编辑
        ProdCatModelEntity isPublishedEntity = prodCatModelDao.selectProductIsPublished(prodCatModelDTO.getModelId());
        if(isPublishedEntity != null){
            throw new MsgException(ResponseCodeEnum.FAILURE,"禁用/启用失败，该品类模板值已上架，请确认后重试！");
        }

        //逻辑删除/启用
        Integer result = prodCatModelDao.deleteModel(prodCatModelDTO);
        if(result > 0 ){
            //添加操作日志
            BaseDTO baseDTO=new BaseDTO();
            BeanUtils.copyProperties(prodCatModelDTO,baseDTO);
            jmOperationLogService.insertUpdateLog(baseDTO,"deleteProdCatModel","ec_prod_cat_model",prodCatModelDTO.getModelId()+"","删除商品品类模板，逻辑删除/启用");
            return ResponseCodeEnum.SUCCESSED;
        }
        return ResponseCodeEnum.PRODCATID_DELETE_FAIL;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public ResponseCodeEnum realDeleteProdCatModel(ProdCatModelDTO prodCatModelDTO) {
        ProdCatModelEntity prodCatModelEntity=prodCatModelDao.selectByPrimaryKey(prodCatModelDTO.getModelId());
        if(prodCatModelEntity == null){
            throw new MsgException(ResponseCodeEnum.FAILURE,"删除失败，该品类模板值已上架，请确认后重试！");
        }
        //判断是否能删除、禁用或者启用、编辑
        ProdCatModelEntity isPublishedEntity = prodCatModelDao.selectProductIsPublished(prodCatModelDTO.getModelId());
        if(isPublishedEntity != null){
            throw new MsgException(ResponseCodeEnum.FAILURE,"删除失败，该品类模板值已上架，请确认后重试！");
        }
        //先删除模板
        prodCatModelDao.deleteByPrimaryKey(prodCatModelDTO.getModelId());
        Example example=new Example(ProdCatModelValueEntity.class);
        example.createCriteria().andCondition("model_id=",prodCatModelDTO.getModelId());
        //再删除对应所有模板属性值
        prodCatModelValueDao.deleteByExample(example);

        //添加操作日志
        jmOperationLogService.insertDeleteLog(prodCatModelDTO.getAddUid(),"realDeleteProdCatModel","ec_prod_cat_model",
                prodCatModelDTO.getModelId()+"","删除商品品类模板");
        return ResponseCodeEnum.SUCCESSED;
    }

    /**
     * 判断是否能删除，禁用或者启用
     * @param prodCatModelDTO
     */
//    private void judgmentDelete(ProdCatModelDTO prodCatModelDTO,String type){
//        //查询上加单品的品类模板值id，ids以逗号隔开
//        String ids= productSkuDao.selectModelValueInProduct();
//        String[] array = ids.split(",");
//        //set集合去重
//        Set<String> allSet = new HashSet<>();
//        for(int i=0;i<array.length;i++){
//            allSet.add(array[i]);
//        }
//        //该模板下的所有模板值id
//        Set<String> cmIdSet=prodCatModelValueDao.selectCmIdByModelId(prodCatModelDTO.getModelId());
//        //取交集，如果有交集，那么说明该品类模板值已上架，不可删除
//        allSet.retainAll(cmIdSet);
//        //上架的模板值不能删除
//        if(allSet.size() > 0){
//            if(type.equals(EDIT)){
//                throw new MsgException(ResponseCodeEnum.FAILURE,"编辑失败，该品类模板值已上架，请确认后重试！");
//            }
//            if(type.equals(DELETE)){
//                throw new MsgException(ResponseCodeEnum.FAILURE,"禁用/启用失败，该品类模板值已上架，请确认后重试！");
//            }
//            if(type.equals(REAL_DELETE)){
//                throw new MsgException(ResponseCodeEnum.FAILURE,"删除失败，该品类模板值已上架，请确认后重试！");
//            }
//        }
//    }
}
